package com.aiyige.page.my.settings.acount;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.eventbus.EventChangePhoneNumberSuccess;
import com.aiyige.model.SmsCode;
import com.aiyige.model.response.ErrorResponse;
import com.aiyige.page.login.callbacks.ITimerCallBack;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.VerifyCodeManager;
import com.aiyige.utils.widget.VerifyCodeInputView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.vondear.rxtools.RxTool;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 修改手机号（验证原手机）
 * xiachao
 */
@Route(path = ARouterConfig.ChangePhoneNumberVerifyPage)
public class ChangePhoneNumberVerifyPage extends BaseActivity implements ITimerCallBack {


    @BindView(R.id.tv_mobile)
    TextView tvMobile;
    @BindView(R.id.widget_verify_code)
    VerifyCodeInputView widgetVerifyCode;
    @BindView(R.id.btn_send_verify_code)
    Button btnSendVerifyCode;
    @BindView(R.id.btn_next)
    Button btnNext;

    SmsCode smsCode;

    boolean sending = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_change_phone_number_verify);
        ButterKnife.bind(this);

        widgetVerifyCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                checkInput();
            }
        });
        widgetVerifyCode.setHint("");
        VerifyCodeManager.getInstance().addLoginCallBack(this);
        fillViews();
        setAutoRegisterEventBus(true);
    }

    private void checkInput() {
        boolean isNull = true;
        if (!isEmpty(getVerifyCode())
                && getVerifyCode().length() == 6) {
            isNull = false;
        }
        btnNext.setEnabled(!isNull);
    }



    public String getVerifyCode() {
        return widgetVerifyCode.getVerifyCode();
    }


    private void fillViews() {
        String mobile = AccountUtil.getMobile() == null ? "":AccountUtil.getMobile();
        tvMobile.setText(mobile);
    }

    private String getPhone() {
        return AccountUtil.getMobile();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        VerifyCodeManager.getInstance().removeLoginCallBack(this);
    }

    @Override
    public void onTick(long l) {
        //防止计时过程中重复点击
        btnSendVerifyCode.setClickable(false);
        btnSendVerifyCode.setText((l / 1000) + "s");
        btnSendVerifyCode.setTextColor(ContextCompat.getColor(this,R.color.zwcolor_gray_b1b5c1));
    }

    @Override
    public void onFinish() {
        btnSendVerifyCode.setTextColor(ContextCompat.getColor(this,R.color.zwcolor_black_111111));
        //重新给Button设置文字
        btnSendVerifyCode.setText(getResources().getString(R.string.get_verification_code));
        //设置可点击
        btnSendVerifyCode.setClickable(true);
    }

    private void sendVerifyCode() {
        if (sending) {
            return;
        }

        VerifyCodeManager.getInstance().tCaptchaDialog(this, new VerifyCodeManager.TCaptchaCallBack() {
            @Override
            public void success() {
                sending = true;
                ApiManager.getService().fetchByMobile(getPhone(), "changeMobileOld").enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(final Call<ResponseBody> call, final Response<ResponseBody> response) {
                        sending = false;
                        try {
                            if (response.isSuccessful()) {
                                smsCode = JsonUtil.toObject(response.body().string(), SmsCode.class);
                                VerifyCodeManager.getInstance().start();
                            } else {
                                ErrorResponse data = JsonUtil.toObject(response.errorBody().string(), ErrorResponse.class);
                                onFailure(call,new Throwable(data.getMessage()));
                            }
                        } catch (Exception e) {
                            try {
                                onFailure(call,new Throwable(e.toString()));
                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        sending = false;
                        if (t != null) {
                            ToastX.show(t.getMessage());
                        }
                    }
                });
            }

            @Override
            public void failed() {

            }
        });


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onChangeSuccessEventBuss(EventChangePhoneNumberSuccess eventChangePhoneNumberSuccess) {
        if (eventChangePhoneNumberSuccess != null) {
            finish();
        }
    }


    @OnClick({R.id.btn_send_verify_code, R.id.btn_next,R.id.rl_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_send_verify_code:
                sendVerifyCode();
                break;
            case R.id.btn_next:
                String mobile = AccountUtil.getMobile() == null ? "":AccountUtil.getMobile();
                if (smsCode != null && !TextUtils.isEmpty(mobile) && !TextUtils.isEmpty(getVerifyCode())&& smsCode.getMobile().equals(mobile) && RxTool.Md5(getVerifyCode()).equals(smsCode.getCode())) {
                    VerifyCodeManager.getInstance().cancel();
                    VerifyCodeManager.getInstance().removeLoginCallBack(this);
                    ARouter.getInstance().build(ARouterConfig.ChangePhoneNumberInputPage).withString("code",getVerifyCode()).navigation();
                } else {
                    ToastX.show("验证码不正确");
                }
                break;
            case R.id.rl_back:
                finish();
                break;
        }
    }
}
